package com.example.bluetooth.ui


import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.example.bluetooth.databinding.DialogBottomBinding


abstract class BottomDialog : DialogFragment() {

    abstract val TAG: String

    abstract val title: String
    abstract val desc: String
    abstract val allow: String
    abstract val deny: String
    abstract val allowCallback: () -> Unit
    abstract val denyCallback: () -> Unit

    open val canceledOnTouchOutside = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        initWindow()
        val rootView = initView(inflater, container)
        return rootView
    }

    private fun initWindow() {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog?.setCanceledOnTouchOutside(canceledOnTouchOutside)
        val window = dialog?.window
        window?.decorView?.background = Color.TRANSPARENT.toDrawable()
        val wlp = window?.attributes
        wlp?.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
        wlp?.width =
            DisplayUtils.getScreenWidth(requireContext()) - DisplayUtils.dp2px(requireContext(), 40)
        wlp?.y = DisplayUtils.dp2px(requireContext(), 20)
        window?.setAttributes(wlp)
    }

    private fun initView(inflater: LayoutInflater, container: ViewGroup?): View {
        val layoutBinding = DialogBottomBinding.inflate(inflater, container, false)
        layoutBinding.title.text = title
        layoutBinding.desc.text = desc
        layoutBinding.allow.text = allow
        layoutBinding.deny.text = deny
        layoutBinding.allow.setOnClickListener {
            allowCallback.invoke()
        }
        layoutBinding.deny.setOnClickListener {
            denyCallback.invoke()
        }
        return layoutBinding.root
    }

    fun showDialog(fragmentManager: FragmentManager) {
        show(fragmentManager, TAG)
    }
}